<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import request from '../../utils/sj-request'
import { ElMessage } from 'element-plus'

// 定义props
const props = defineProps({
  // 选中的答案类型ID
  answerTypeId: {
    type: Number,
    default: null
  },
  // 已有的答案ID（编辑模式）
  answerId: {
    type: Number,
    default: null
  }
})

// 定义emit事件
const emit = defineEmits(['update:answerId'])

// 答案类型列表
const answerTypeList = ref([])
// 选中的答案类型
const selectedAnswerType = ref(null)

// 客观题答案选项
const objectiveAnswerOptions = ref([
  { label: 'A', content: '', isCorrect: false },
  { label: 'B', content: '', isCorrect: false },
  { label: 'C', content: '', isCorrect: false },
  { label: 'D', content: '', isCorrect: false }
])

// 主观题答案
const subjectiveAnswer = reactive({
  referenceAnswer: '',
  gradingRules: ''
})

// 加载状态
const loading = ref(false)

// 获取答案类型列表
const fetchAnswerTypes = async () => {
  try {
    const res = await request({
      url: 'answer-type/list',
      method: 'get'
    })
    answerTypeList.value = res.data || []
  } catch (error) {
    console.error('获取答案类型列表失败:', error)
  }
}



// 获取答案详情
const fetchAnswerDetail = async (answerId) => {
  if (!answerId) return
  
  loading.value = true
  try {
    // 根据后端代码，客观题ID为1，主观题ID为2
    const url = props.answerTypeId === 1
      ? `answer/objective/${answerId}`
      : `answer/subjective/${answerId}`
    
    const res = await request({
      url,
      method: 'get'
    })
    
    if (res.data) {
      if (props.answerTypeId === 1) {
        // 解析客观题答案
        try {
          // 确保questionAnswer字段存在且是字符串
          if (res.data.questionAnswer && typeof res.data.questionAnswer === 'string') {
            const answerData = JSON.parse(res.data.questionAnswer)
            objectiveAnswerOptions.value = answerData.options || []
          } else {
            console.error('答案数据格式错误')
            ElMessage.warning('获取答案数据格式错误')
          }
        } catch (e) {
          console.error('解析答案数据失败:', e)
          ElMessage.warning('解析答案数据失败')
        }
      } else {
        // 设置主观题答案
        subjectiveAnswer.referenceAnswer = res.data.referenceAnswer || ''
        subjectiveAnswer.gradingRules = res.data.gradingRules || ''
      }
    } else {
      ElMessage.warning('未找到答案数据')
    }
  } catch (error) {
    console.error('获取答案详情失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理答案类型变化
const handleAnswerTypeChange = (typeId) => {
  const type = answerTypeList.value.find(item => item.id === typeId)
  selectedAnswerType.value = type ? type.name : null
  
  // 重置答案相关数据
  objectiveAnswerOptions.value = [
    { label: 'A', content: '', isCorrect: false },
    { label: 'B', content: '', isCorrect: false },
    { label: 'C', content: '', isCorrect: false },
    { label: 'D', content: '', isCorrect: false }
  ]
  subjectiveAnswer.referenceAnswer = ''
  subjectiveAnswer.gradingRules = ''
}

// 添加选项（针对客观题）
const addOption = () => {
  objectiveAnswerOptions.value.push({
    label: String.fromCharCode(65 + objectiveAnswerOptions.value.length), // A, B, C...
    content: '',
    isCorrect: false
  })
}

// 移除选项
const removeOption = (index) => {
  objectiveAnswerOptions.value.splice(index, 1)
  // 重新标记选项标签
  objectiveAnswerOptions.value.forEach((option, idx) => {
    option.label = String.fromCharCode(65 + idx)
  })
}

// 保存答案
const saveAnswer = async () => {
  try {
    let answerId = null
    
    if (props.answerTypeId === 1) {
      // 验证客观题答案
      const hasEmptyOption = objectiveAnswerOptions.value.some(option => !option.content.trim())
      if (hasEmptyOption) {
        ElMessage.warning('选项内容不能为空')
        return null
      }
      
      const hasCorrectOption = objectiveAnswerOptions.value.some(option => option.isCorrect)
      if (!hasCorrectOption) {
        ElMessage.warning('请至少选择一个正确答案')
        return null
      }
      
      // 处理客观题答案
      const correctOptions = objectiveAnswerOptions.value
        .filter(option => option.isCorrect)
        .map(option => option.label)
        .join(',')
      
      const answerData = {
        answerTypeId: props.answerTypeId, // 添加答案类型ID
        questionAnswer: JSON.stringify({
          options: objectiveAnswerOptions.value,
          correctAnswer: correctOptions
        })
      }
      
      // 保存客观题答案
      const res = await request({
        url: 'answer/objective',
        method: props.answerId ? 'put' : 'post',
        data: props.answerId ? { ...answerData, id: props.answerId } : answerData
      })
      
      answerId = res.data
    } else if (props.answerTypeId === 2) {
      // 验证主观题答案
      if (!subjectiveAnswer.referenceAnswer.trim()) {
        ElMessage.warning('参考答案不能为空')
        return null
      }
      
      // 处理主观题答案
      const answerData = {
        answerTypeId: props.answerTypeId, // 添加答案类型ID
        referenceAnswer: subjectiveAnswer.referenceAnswer,
        gradingRules: subjectiveAnswer.gradingRules
      }
      
      // 保存主观题答案
      const res = await request({
        url: 'answer/subjective',
        method: props.answerId ? 'put' : 'post',
        data: props.answerId ? { ...answerData, id: props.answerId } : answerData
      })
      
      answerId = res.data
    } else {
      ElMessage.warning('请先选择答案类型')
      return null
    }
    
    // 更新答案ID
    emit('update:answerId', answerId)
    return answerId
  } catch (error) {
    console.error('保存答案失败:', error)
    ElMessage.error('保存答案失败')
    return null
  }
}



// 监听props变化
watch(() => props.answerTypeId, (newVal) => {
  if (newVal) {
    handleAnswerTypeChange(newVal)
  }
})

watch(() => props.answerId, (newVal) => {
  if (newVal && props.answerTypeId) {
    // 如果有答案ID，说明是编辑模式，获取答案详情
    fetchAnswerDetail(newVal)
  }
})

// 组件挂载时获取数据
onMounted(async () => {
  await fetchAnswerTypes()
  
  if (props.answerTypeId) {
    handleAnswerTypeChange(props.answerTypeId)
  }
  
  if (props.answerId) {
    fetchAnswerDetail(props.answerId)
  }
})

// 对外暴露方法
defineExpose({
  saveAnswer
})
</script>

<template>
  <div class="answer-selector">
    <!-- 创建答案 -->
    <div class="create-answer">
      <!-- 客观题答案设置 -->
      <div v-if="props.answerTypeId === 1" class="objective-answer">
        <h4>选项设置</h4>
        
        <div
          v-for="(option, index) in objectiveAnswerOptions"
          :key="index"
          class="option-item"
        >
          <div class="option-header">
            <span class="option-label">{{ option.label }}</span>
            <el-checkbox v-model="option.isCorrect">正确答案</el-checkbox>
            <el-button
              type="danger"
              size="small"
              circle
              icon="Delete"
              @click="removeOption(index)"
              :disabled="objectiveAnswerOptions.length <= 2"
            />
          </div>
          
          <el-input
            v-model="option.content"
            type="textarea"
            :rows="2"
            placeholder="请输入选项内容"
          />
        </div>
        
        <div class="add-option">
          <el-button type="primary" plain @click="addOption">添加选项</el-button>
        </div>
      </div>
      
      <!-- 主观题答案设置 -->
      <div v-else-if="props.answerTypeId === 2" class="subjective-answer">
        <h4>参考答案</h4>
        <el-input
          v-model="subjectiveAnswer.referenceAnswer"
          type="textarea"
          :rows="6"
          placeholder="请输入参考答案"
        />
        
        <h4>评分标准</h4>
        <el-input
          v-model="subjectiveAnswer.gradingRules"
          type="textarea"
          :rows="4"
          placeholder="请输入评分标准"
        />
      </div>
      
      <!-- 未选择答案类型 -->
      <div v-else class="no-answer-type">
        <el-empty description="请先选择答案类型" />
      </div>
    </div>
  </div>
</template>

<style scoped>
.answer-selector {
  margin-top: 20px;
}

.option-label {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f0f2f5;
  border-radius: 50%;
  flex-shrink: 0;
}

.option-label.correct {
  background-color: #67c23a;
  color: white;
}

.option-content {
  flex: 1;
  word-break: break-all;
}

.objective-answer,
.subjective-answer {
  margin-top: 20px;
}

.option-item {
  margin-bottom: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
}

.option-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.option-label {
  font-weight: bold;
  margin-right: 15px;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f0f2f5;
  border-radius: 50%;
}

.add-option {
  margin-top: 20px;
}

h4 {
  margin-top: 20px;
  margin-bottom: 15px;
  font-weight: normal;
  color: #606266;
}
</style>